package com.shoubei.cashiedesk.base;

import android.app.Application;
import android.content.Context;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.WindowManager;
import android.widget.Toast;

import com.LibSharedPreferences.Preferences;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.Utils;
import com.raizlabs.android.dbflow.config.FlowManager;
import com.shoubei.cashiedesk.bean.PrinterInfo;
import com.shoubei.cashiedesk.di.component.ApplicationComponent;
import com.shoubei.cashiedesk.di.component.DaggerApplicationComponent;
import com.shoubei.cashiedesk.di.module.ApplicationModule;
import com.shoubei.cashiedesk.event.LoginEvent;
import com.shoubei.cashiedesk.serialPort.PrintAndKexianDevice;
import com.shoubei.cashiedesk.shoubei.BuildConfig;
import com.shoubei.cashiedesk.shoubei.R;
import com.shoubei.cashiedesk.utils.aidl.SunmiGuestCallback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import me.yokeyword.fragmentation.Fragmentation;
import sunmi.ds.DSKernel;

/**
 * Created by lw on 2018/1/18.
 */

public class App extends Application {
    private ApplicationComponent mApplicationComponent;
    private static App mInstance;
    public int width, height, screenDensity;
    public Preferences pre;
    public LoginEvent loginInfo;
    public LoginEvent.MerchantBean merchant;
    public LoginEvent.ManagerBean managerBean;
    public Map<String, Object> results = new HashMap<String, Object>();// 小票打印logo和广告集合
    // 获取到主线程的Handler`
    public static Handler mMainThreadHandler;
    private static Toast toast;
    // 商米客显对象初始化
    public DSKernel mDSKernel;
    public PrinterInfo lablePrintInfo;// 标签打印机
    // 客显设置
    public PrintAndKexianDevice kexianDevice =new PrintAndKexianDevice();

     String getNameCn;// 标签打印机
    // 打印机设置
    public PrintAndKexianDevice printDevice =new PrintAndKexianDevice();

    public List<PrinterInfo> printerList = new ArrayList<PrinterInfo>();// 小票机List
    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
        initApplicationComponent();
        mMainThreadHandler = new Handler();
        pre = new Preferences(this);
        Utils.init(this);
        intARouter();
        FlowManager.init(this);
        initCloudChannel(this);
//        kexianDevice = db.findById(PrintAndKexianDevice.class, PrintAndKexianDevice.type_kexian);
        JPushInterface.setDebugMode(true); 	// 设置开启日志,发布时请关闭日志
        JPushInterface.init(this);     		// 初始化 JPush
        // 商米客显对象初始化
        App.getInstance().mDSKernel = DSKernel.newInstance();
        App.getInstance().mDSKernel.init(this, new SunmiGuestCallback());
        Fragmentation.builder()
                .stackViewMode(Fragmentation.BUBBLE)                // 显示悬浮球 ; 其他Mode:SHAKE: 摇一摇唤出   NONE：隐藏
                .debug(BuildConfig.DEBUG)
                .install();
        if (width == 0) {
            WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
            DisplayMetrics metrics = new DisplayMetrics();
            windowManager.getDefaultDisplay().getMetrics(metrics);
            width = metrics.widthPixels;
            height = metrics.heightPixels;
            screenDensity = metrics.densityDpi;
        }



    }


    /**
     * 初始化路由
     */
    private void intARouter() {
        if (BuildConfig.DEBUG) {           // 这两行必须写在init之前，否则这些配置在init过程中将无效
            ARouter.openLog();     // 打印日志
            ARouter.openDebug();   // 开启调试模式(如果在InstantRun模式下运行，必须开启调试模式！线上版本需要关闭,否则有安全风险)
        }
        ARouter.init(this); // 尽可能早，推荐在Application中初始化
    }

    /**
     * 初始化ApplicationComponent
     */
    private void initApplicationComponent() {
        mApplicationComponent = DaggerApplicationComponent.builder()
                .applicationModule(new ApplicationModule(this))
                .build();
    }

    public ApplicationComponent getApplicationComponent() {
        return mApplicationComponent;
    }

    public static Context getAppContext() {
        return mInstance.getApplicationContext();
    }

    public static App getInstance() {
        return mInstance;
    }

    public static void toast(final String str) {
        if (str == null) {
            return;
        }
        try {
            mMainThreadHandler.post(new Runnable() {

                @Override
                public void run() {

                    if (toast != null) {
                        toast.cancel();
                    }

                    toast = Toast.makeText(mInstance, str, Toast.LENGTH_SHORT);
                    // toast.setGravity(Gravity.TOP, 0, 20);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化云推送通道
     * @param applicationContext
     */
    private void initCloudChannel(Context applicationContext) {
        PushServiceFactory.init(applicationContext);
        CloudPushService pushService = PushServiceFactory.getCloudPushService();
        pushService.register(applicationContext, new CommonCallback() {
            @Override
            public void onSuccess(String response) {
                Log.e("initCloudChannel", "init cloudchannel success");
            }
            @Override
            public void onFailed(String errorCode, String errorMessage) {
                Log.e("initCloudChannel", "init cloudchannel failed -- errorcode:" + errorCode + " -- errorMessage:" + errorMessage);
            }
        });
    }
}
